#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/7/29 14:02
# @Author  : Fairy Huang
# @File    : common.py
# @Project: LabCrawler
import logging
import hashlib
import six
import re
import settings


class log_helper():
    def __init__(self, name):
        self.logger = logging.getLogger(name)
        fm = logging.Formatter('%(asctime)s %(filename)s(%(lineno)d) %(levelname)s %(name)s - %(message)s')
        if settings.DEBUG:
            lh = logging.handlers.TimedRotatingFileHandler('log/' + name + ".log", when='midnight')
            lh.setFormatter(fm)
            lh.suffix = "%Y-%m-%d"
            self.logger.addHandler(lh)
            self.logger.setLevel(logging.DEBUG)
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(fm)
        self.logger.addHandler(console)


def get_md5(url):
    if isinstance(url, str):
        url = url.encode("utf-8")
    m = hashlib.md5()
    m.update(url)
    return m.hexdigest()


def extract_num(text, prefix=""):
    #从字符串中提取出数字，可指定数字的前缀字符串
    match_re = re.match(".*%s?(\d+).*" % prefix, text)
    if match_re:
        nums = int(match_re.group(1))
    else:
        nums = 0
    return nums


def extract_json(text):
    #从字符串中提取出JSON
    match_re = re.match(".*?({.*}).*", text)
    if match_re:
        json_data = match_re.group(1)
    else:
        json_data = {}
    return json_data


def bytes_to_str(s, encoding='utf-8'):
    """Returns a str if a bytes object is given."""
    if six.PY3 and isinstance(s, bytes):
        return s.decode(encoding)
    return s